package com.micosco.taskremind.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.room.Room;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.micosco.taskremind.R;
import com.micosco.taskremind.data.TaskDatabase;
import com.micosco.taskremind.data.TaskList;
import com.micosco.taskremind.ui.handler.TaskListRefreshHandler;

import java.util.Objects;


/**
 * A fragment representing a list of Tasks.
 */
public class TaskListFragment extends Fragment {

    // TODO: Customize parameter argument names
    private static final String ARG_COLUMN_COUNT = "column-count";
    // TODO: Customize parameters
    private int mColumnCount = 1;

    TaskListRefreshHandler handler;

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public TaskListFragment() {
    }

    // TODO: Customize parameter initialization
    @SuppressWarnings("unused")
    public static TaskListFragment newInstance(int columnCount) {
        TaskListFragment fragment = new TaskListFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_COLUMN_COUNT, columnCount);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_task_list, container, false);

        // Set the adapter
        if (view instanceof RecyclerView) {
            Context context = view.getContext();
            TaskListViewModel viewModel =
                    new ViewModelProvider(this).get(TaskListViewModel.class);
            TaskDatabase database = Room.databaseBuilder(context, TaskDatabase.class,
                    "tasks").build();
            new Thread(
                    () -> viewModel.getTasks().postValue(database.taskDAO().findAllUnfinished()));

            RecyclerView recyclerView = (RecyclerView) view;

            if (mColumnCount <= 1) {
                recyclerView.setLayoutManager(new LinearLayoutManager(context));
            } else {
                recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
            }
            TaskListRecyclerViewAdapter adapter = new TaskListRecyclerViewAdapter(
                    viewModel.getTasks().getValue());
            adapter.setOnItemClickListener((view1, position) -> {
                Intent intent = new Intent(requireActivity().getApplicationContext(),
                        TaskInfoActivity.class);
                intent.putExtra("TYPE", TaskInfoActivity.TASK_INFO);
                TaskViewHolder viewHolder = (TaskViewHolder)
                        recyclerView.findViewHolderForAdapterPosition(position);
                if (viewHolder != null) {
                    intent.putExtra("UID", viewHolder.mItem.getUID());
                    startActivity(intent);
                }
            });
            recyclerView.setAdapter(adapter);

            handler = new TaskListRefreshHandler(recyclerView);
            handler.startRefresh();
        }
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        handler.stopRefresh();
    }
}

